import tkinter
import tkinter.filedialog
import tkinter.messagebox
import os
from PIL import ImageGrab, Image
from time import sleep

root = tkinter.Tk()
root.geometry('100x40+400+300')
root.resizable(False, False)

class MyCapture:
    def __init__(self, png):
        self.X = tkinter.IntVar(value=0)
        self.Y = tkinter.IntVar(value=0)

        screenWidth = root.winfo_screenwidth()
        screenHeight = root.winfo_screenheight()
        
        self.top = tkinter.Toplevel(root, width=screenWidth, height=screenHeight)
        self.top.overrideredirect(True)
        self.canvas = tkinter.Canvas(self.top, bg='white', width=screenWidth, height=screenHeight)
        self.image = tkinter.PhotoImage(file=png)
        self.canvas.create_image(screenWidth // 2, screenHeight // 2, image=self.image)

        def onLeftButtonDown(event):
            im = Image.open(png)
            color = im.getpixel((event.x_root, event.y_root))[:3]  # 使用 x_root 和 y_root 获取全局坐标
            msg = str(color) + '\n'
            color = '#' + ''.join(map(lambda X: hex(X)[2:].zfill(2), color))  # 确保每个颜色分量都是两位十六进制数
            msg += color
            tkinter.messagebox.showinfo('', msg)
            self.top.destroy()

        self.canvas.bind('<Button-1>', onLeftButtonDown)
        self.canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES)

def buttonCaptureClick():
    root.iconify()  # 最小化窗口
    sleep(0.2)
    filename = 'temp.png'
    im = ImageGrab.grab()
    im.save(filename)
    im.close()
    w = MyCapture(filename)
    w.top.wait_window()  # 等待窗口关闭
    root.deiconify()  # 恢复窗口
    os.remove(filename)

buttonCapture = tkinter.Button(root, text='Capture', command=buttonCaptureClick)
buttonCapture.place(x=10, y=10, width=80, height=20)

root.mainloop()